package cmd

import (
	"context"
	"fmt"
	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/swagger/v2"
	"goAdminV1/internal/middleware"
	"goAdminV1/route"
	"goAdminV1/utility"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			address := g.Cfg().MustGet(ctx, "server.address").String()
			port := g.Cfg().MustGet(ctx, "server.port").Int()
			serverURL := fmt.Sprintf("%s:%d", address, port)
			//swaggerURL := fmt.Sprintf("%s:%d/swagger", address, port)
			// 配置服务器监听地址为假域名和端口
			s.SetAddr(serverURL)
			s.Plugin(&swagger.Swagger{})
			// 设置 Swagger UI 地址 为原先的 UI
			s.SetSwaggerUITemplate(utility.MySwaggerUITemplate)
			//添加 Swagger 安全定义
			s.GetOpenApi().Components.SecuritySchemes = utility.GetSwaggerSecurityConfig()
			// 设置全局安全要求
			s.GetOpenApi().Security = utility.GetSwaggerSecurityRequirements()
			// 添加全局 CORS 中间件
			s.Use(middleware.CORS)
			s.Use(middleware.LogRequestParams)
			s.Group("/", func(group *ghttp.RouterGroup) {
				// 注册响应包装中间件
				group.Middleware(middleware.ResponseWrapper)
				route.RegisterRoutes(group)
			})
			s.SetPort(8000)
			s.Run()
			return nil
		},
	}
)
